import os
import secrets
from PIL import Image
from flask import url_for, current_app
from flask_mail import Message

from blog import mail


def send_reset_email(user):
    """发送重置密码邮箱"""
    token = user.get_reset_token()
    msg = Message(
        subject='重置密码',
        # sender=app.config['ADMIN_EMAIL'],
        sender=current_app.config['MAIL_USERNAME'],
        recipients=[user.email],
    )
    # url_for参数_external=True显示完整域名
    msg.body = f'''点击下面连接进行重置密码:
{url_for('password_reset', token=token, _external=True)}
如果你没有进行该请求操作，请忽略该邮件。
    '''
    mail.send(msg)


def save_img(form_data):  # form_data: FileStorage对象
    """
    :param form_data: 用户上传个人头像数据 如： form.avatar.data
    :return: 返回头像图片的名字

    使用Pillow模块更改用户头像尺寸
    并保存到 static/avatars目录下
    """
    random_hex = secrets.token_hex(8)
    _, ext = os.path.splitext(form_data.filename)
    avatar_filename = random_hex + ext
    avatar_path = os.path.join(current_app.root_path, 'static/avatars', avatar_filename)

    # form_data.save(avatar_path)
    # 更改用户头像尺寸
    img_size = (120, 120)
    i = Image.open(form_data)
    i.thumbnail(img_size)
    i.save(avatar_path)

    return avatar_filename
